package cn.qingfeng.a004_chat_v3.server.handler;

import cn.qingfeng.a004_chat_v3.message.LoginRequestMessage;
import cn.qingfeng.a004_chat_v3.message.LoginResponseMessage;
import cn.qingfeng.a004_chat_v3.server.session.Session;
import cn.qingfeng.a004_chat_v3.server.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

@ChannelHandler.Sharable
public class LoginHandler extends SimpleChannelInboundHandler<LoginRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, LoginRequestMessage msg) throws Exception {
        // username + " login " + password
        final Session session = SessionFactory.getSession();

        if (msg == null) {
            return;
        }

        String username = msg.getUsername();
        String password = msg.getPassword();
        boolean loginFlag = false;
        if ("123".equals(password)) {
            loginFlag = true;
        }
        if (loginFlag) {
            session.bind(username, ctx.channel());
            ctx.writeAndFlush(new LoginResponseMessage(true, "登录成功"));
        } else {
            ctx.writeAndFlush(new LoginResponseMessage(false, "用户名或密码不正确"));
        }
    }
}
